/*
 * Copyright (c) 2019. ascend 版权所有禁止转载。
 */

package cn.edu.zua.demo13.controller;

import cn.edu.zua.demo13.entity.TestUserEntity;
import cn.edu.zua.demo13.jpa.TestUserJpa;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 说明：
 *
 * @author ascend
 * 2019/1/28 10:52
 */
@RestController
@RequestMapping("/user")
public class TestUserController {
    private TestUserJpa userJPA;

    @Autowired
    public TestUserController(TestUserJpa userJPA) {
        this.userJPA = userJPA;
    }

    @GetMapping("/list")
    public List<TestUserEntity> list() {
        return userJPA.findAll();
    }

    @GetMapping("/addUser")
    public TestUserEntity add() {
        TestUserEntity user = new TestUserEntity();
        user.setUserName("erdan");
        user.setUserPassword("erdan");
        user.setAge(23);
        user.setGmtCreated(LocalDateTime.now());
        user.setGmtModified(LocalDateTime.now());
        return userJPA.save(user);
    }

    @GetMapping(path = "/delete")
    public String delete(Long id) {
        userJPA.deleteById(id);
        return "用户信息删除成功";
    }

    @GetMapping(path = "/age")
    public List<TestUserEntity> age() {
        return userJPA.nativeQuery(20);
    }

    @GetMapping("/deleteWhere")
    public String deleteWhere() {
        userJPA.deleteWhere("erdan", "erdan");
        return "自定义sql删除数据成功";
    }

    @GetMapping(path = "/cutPage")
    public List<TestUserEntity> curPage(int pageNo) {
        TestUserEntity user = new TestUserEntity();
        user.setPageSize(2);
        user.setSort("desc");
        user.setPageNo(pageNo);
        // 获取排序对象
        Sort.Direction sortDirection = Sort.Direction.ASC.toString().equalsIgnoreCase(user.getSort()) ? Sort.Direction.ASC : Sort.Direction.DESC;
        Sort sort = new Sort(sortDirection, user.getSortColumn());
        // 创建分页对象
        PageRequest pageRequest = PageRequest.of(user.getPageNo() - 1, user.getPageSize(), sort);
        // 执行分页查询
        return userJPA.findAll(pageRequest).getContent();
    }

    private void t() {
        String sql = "select * from test_user";
        JdbcTemplate jdbcTemplate = new JdbcTemplate(null);
        jdbcTemplate.execute(sql);
    }
}
